package xyz.jcat.common.web;

import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.validation.FieldError;
import xyz.jcat.common.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class MethodParameterValidateUtils {

    private static final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static void validate(Object obj) {
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<Object>> result = validator.validate(obj, new Class[0]);
        if(CollectionUtils.isNotEmpty(result)) {
            throw new ParameterErrorException(convert(result));
        }
    }

    public static List<ParameterErrorVo> convert(List<FieldError> fieldErrors) {
        List<ParameterErrorVo> list = new ArrayList<>(fieldErrors.size());
        for (FieldError fieldError : fieldErrors) {
            list.add(new ParameterErrorVo(fieldError.getField(), fieldError.getDefaultMessage()));
        }
        return list;
    }

    public static List<ParameterErrorVo> convert(Set<? extends ConstraintViolation<?>> errors) {
        List<ParameterErrorVo> list = new ArrayList<>(errors.size());
        for (ConstraintViolation error : errors) {
            list.add(new ParameterErrorVo(((PathImpl) error.getPropertyPath()).getLeafNode().getName(), error.getMessage()));
        }
        return list;
    }
}
